package edu.ajou.scw;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.catalina.Session;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class Login
 */
@WebServlet("/Login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private DatabaseConnector conn;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();

        conn = new DatabaseConnector();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
    
    final int PC_PORT = 8788;
    
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String type = (String)request.getParameter("type"); // login or register
		
		String id = (String)request.getParameter("id");
		String pwd = (String)request.getParameter("password");
		//String email = (String)request.getParameter("email");
		String device = (String)request.getParameter("device");
		String key = (String)request.getParameter("key");
		//String name = (String)request.getParameter("name");
		
		PrintWriter respOut = response.getWriter();
		
					
			if (conn.auth(id, pwd))
			{
				Log.d(id + " loged in");
				
				UserInfo userInfo = conn.getUserInfo(id, true).get(0);
				JSONObject obj = new JSONObject();
				obj.put("status", "ok");
				obj.put("id", id);
				obj.put("name", userInfo.getName());
				obj.put("email", userInfo.getEmail());
				obj.put("image", userInfo.getImage());
				//TODO
				//obj.put("image", userInfo.getImage());
				respOut.println(obj.toJSONString());
				
				if (device.equalsIgnoreCase("pc"))
				{
					key = request.getRemoteAddr() + ":" + PC_PORT;
				}
					
				int result = conn.query(String.format("update `login_info` set `device`=\"%s\", `connection`=\"%s\", `logon`=\"1\" where `id` = \"%s\"", device, key, id));
				if (result == 0)
				{
					String sql = String.format("insert into `login_info` (`id`, `device, `connection`, `logon`) values (\"%s\",\"%s\",\"%s\", \"1\")", id,device,key);
					conn.query(sql);
				}
			}
			else
			{
				Log.d("Login fail: " + id);
				respOut.println("{ \"status\": \"fail\" }");
			}
			
		
		/*
		else if (type.equals("register"))
		{
			ArrayList<UserInfo> ui = conn.getUserInfo(id, true);
				
			if (ui != null && ui.size() > 0)
			{
				Log.d("Register fail: " + id + " is already registered.");
				respOut.println("{ \"status\": \"duplicate\" }");
			}
			else
			{
				String sql = String.format("insert into `usr_info` (`id`, `name`, `password`, `email`) values (\"%s\", \"%s\", \"%s\", \"%s\")", id, name, pwd, email);
				int result = conn.query(sql);
				sql = String.format("insert into `login_info` (`id`) values (\"%s\")", id);
				conn.query(sql);
				if (result > 0)
				{	
					Log.d(id + " is registered.");
					UserInfo userInfo = conn.getUserInfo(id, true).get(0);
					JSONObject obj = new JSONObject();
					obj.put("status", "ok");
					obj.put("id", id);
					obj.put("name", userInfo.getName());
					obj.put("email", userInfo.getEmail());
					respOut.println(obj.toJSONString());
				}
				else { 
					respOut.println("{ \"status\": \"fail\" }");
				}
			}
		}
		*/

		respOut.close();
	}

}